package com.philosophy.web.domain.generate;

import com.google.common.hash.HashCode;
import com.google.common.hash.HashFunction;
import com.google.common.hash.Hashing;
import org.springframework.stereotype.Component;

import java.nio.charset.StandardCharsets;
import java.time.LocalDateTime;
import java.time.ZoneOffset;
import java.util.Random;

/**
 * <p>
 * 通过hash的方式映射短链接
 * </p>
 *
 * @author philosophy
 */
@Component
public class GenerateShortUrlByHash extends AbstractGenerateShortUrl {

    /**
     * 盐值的格式化字符串
     */
    protected final String saltFormat = "timestamp=%s,random=%s";

    protected final Random random = new Random();

    /**
     * 获取字符串的唯一标识
     *
     * @param str 字符串
     * @return hash值
     */
    @Override
    protected long getStrIdentity(String str) {
        HashFunction hashFunction = Hashing.murmur3_128();
        HashCode hashCode = hashFunction.hashString(str, StandardCharsets.UTF_8);
        return hashCode.asLong() & this.threshold;
    }

    @Override
    protected String getSalt() {
        long epochSecond = LocalDateTime.now().toEpochSecond(ZoneOffset.UTC);
        //预防高并发两次相同的url请求时间相同,所以加上随机数
        return String.format(saltFormat, epochSecond, random.nextInt(1000));
    }
}
